package com.example.demo.Service;

import com.alibaba.fastjson.JSON;
import com.example.demo.Mappers.GetRecipeListMapper;
import com.example.demo.Mappers.RegistMapper;
import com.example.demo.beans.*;
import com.example.demo.controller.TestController;
import com.example.demo.utils.AppConfigUtils;
import com.example.demo.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2018/4/16.
 * 执行挂号或者预约挂号
 * 取消预约挂号
 */
@Service("ExecRegistService")
public class ExecRegistService {
    private Logger logger = LoggerFactory.getLogger(ExecRegistService.class);
    @Autowired
    private RegistMapper mapper;
    @Autowired
    private GetRecipeListMapper kmapper;
    @Transactional(readOnly = true)
    //@Transactional(rollbackFor = Exception.class)
    public ExecRegistResponse ExecRegistPatient(ExecRegistRequest request){
        logger.error("执行挂号和预约挂号的入参:"+JSON.toJSONString(request));
        //挂号日期
        String yyghrq=request.getDay()+" 00:00:10.000";
        //有效日期
        String yyyxrq=DateUtils.getNextDay(yyghrq,"2");
        //登记日期，一般为当日
        String yydjrq=DateUtils.Getdnowdatexx();
        String DAY=request.getDay()+" 00:00:00.000";
        String czybm= AppConfigUtils.getGhybm();
        String czyxm=AppConfigUtils.getCzyxm();
        String czyks=AppConfigUtils.getGhyks();
        String ywckbm=AppConfigUtils.getYwckbm();
        String ghfsbm=AppConfigUtils.getGhfsbm();
        String fbbm=AppConfigUtils.getFbbm();
        //医生排班信息
        DocDetailBean detailBean=mapper.selectdocdetail(request.getDoctID(),DAY);

        /**当获取到排班信息为空时候执行*/
        if(detailBean==null){
            ExecRegistResponse r1=new ExecRegistResponse();
            r1.setResultCode("1");
            r1.setResultMsg("排班信息获取为空，请检查排班和传入参数是否有误");
            return r1;
        }
        double ghzf=0;
        //  String yy=   ghzfymap.get(detailBean.getTypeID());
        ghzf= Double.valueOf(mapper.Getghzf(request.getTypeID().trim()));
        if(!(Double.valueOf(request.getPayAmt())-ghzf==0))
        { ExecRegistResponse r=new ExecRegistResponse();
            r.setResultCode("1");
            r.setResultMsg("挂号失败！您的缴费金额和应缴金额不等，请到挂号窗口处理！");
            return  r;
        }
//判断微信订单号，如果订单号已经写入系统，则返回交易失败信息给微信，提醒该订单号已经交易
        if(request.getReqtype().trim().equals("1")&&request.getAutoTranNo().trim()!=null)
        { ExecRegTempGetIdBean idBean=new ExecRegTempGetIdBean();
            idBean=mapper.GetOderIdand(request.getAutoTranNo().trim());
            if (idBean!=null){
                if(idBean.getAutoTranNo()!=null){
                    ExecRegistResponse   billTradeResponse1=new ExecRegistResponse();
                    //billTradeResponse1.setResultCode("0");
                    //billTradeResponse1.setResultMsg("提示：该订单已经插入数据库,应该属于二次轮询提交，该提示仅用于提醒前端开发人员！");
                    String ghxh="";
                    if(idBean.getGhxh()!=null){
                        ghxh=idBean.getGhxh();
                    }
                    billTradeResponse1=setResponse1(detailBean,ghxh,yydjrq,ghxh,"提示：该订单已经插入数据库,应该属于二次轮询提交，该提示仅用于提醒前端开发人员！");
                    logger.error("挂号和预约挂号的出参:"+ JSON.toJSONString(billTradeResponse1));
                    return billTradeResponse1;
                }}

        }



//挂号日期与当前日期相差的天数
        int k = DateUtils.daysBetween(yyghrq);
        Long tempyyghid=Long.parseLong(DateUtils.getStringToday()+"000000");
        PatientInfodetail patientInfodetail=mapper.selectpatientdetal(request.getPatientID(),request.getCardNo());
        //请求患者信息为空时候执行
        if(patientInfodetail==null){
            ExecRegistResponse execRegistResponse=new ExecRegistResponse();
            execRegistResponse.setResultCode("1");
            execRegistResponse.setResultMsg("提示：获取患者信息为空，请检查请求参数");

            return execRegistResponse;
        }

        int yyzfbz=0;
        String yyghid="";
        String ghxh="";
        String jsjlid="";
        String ispay="0";
        float fyhj=0;
        //门诊发票信息
        MzdqpjBean mzdqpjBean=mapper.Getmzpjxx(czybm);
        String qshnew=String.valueOf(Long.valueOf(mzdqpjBean.getQsh())+1);
        mapper.updatemzdqqj(qshnew,mzdqpjBean.getQsh(),mzdqpjBean.getJsh(),mzdqpjBean.getFpjlid(),czybm);
        List<GhzlbmBean>list=mapper.selectghzl(request.getDoctID());

        // if(Double.valueOf(request.getPayAmt())>0){
        yyzfbz=1;
        ispay="1";
        // }

        System.out.print("这是k:"+k+"   这是m:"+"这是医生信息:" +detailBean.getDoctName());
        //当挂号时间是预约挂号时执行
        String yyghxh="";
        if(k<0){
            Yygh_ywxh ywxh=mapper.getyyghywxh();
            yyghxh=ywxh.getXh();
            //当天是否首次预约挂号
            int t=DateUtils.daysBetween(ywxh.getSsrq());
            String id="";
            if(t>=1){
                System.out.print("执行到预约挂号这里了");
                id=iftthanone(yyghid,tempyyghid,czybm,yyghrq,ywckbm,patientInfodetail.getSex(),
                        patientInfodetail.getAge(),request.getDoctID(),detailBean.getDeptID(),czyks,
                        yydjrq,yyyxrq,yyzfbz,patientInfodetail,DAY);
            }
            else {
                id=iftlessone(yyghid,tempyyghid,czybm,yyghrq,ywckbm,patientInfodetail.getSex(),
                        patientInfodetail.getAge(),request.getDoctID(),detailBean.getDeptID(),czyks,
                        yydjrq,yyyxrq,yyzfbz,patientInfodetail,DAY,yyghxh);
            }
            AutoOrderBean a=setAutoBean(detailBean,yyghrq,"",id,request,ispay,czybm,czyxm);
            mapper.saveyyjl(a);
            String AutoOderListId=mapper.GetMaxAutoOrderListId();
            //  String Autoid="";
            if(yyzfbz>0){
                PayDetailBean p=setPayBean(patientInfodetail,id,request,czybm,czyxm,AutoOderListId);
                mapper.saverePaybean(p);
                // Autoid=mapper.GetMaxAutoId();
            }

            return  setResponse(detailBean,id,yyghrq,id);

        }

        /**当预约挂号为当日且已经支付时候**/
        if (k==0&&yyzfbz>0){
            Ghxh_YwckBean ghxh_ywckBean=mapper.getGhxhYwxh();
            String tempghxh=ghxh_ywckBean.getXh();
            int m=DateUtils.daysBetween(ghxh_ywckBean.getSsrq());
            if(m>=1){
                ghxh=ifmthanone(tempyyghid,request.getTypeID(),ghfsbm,fbbm,request.getPatientID(),czybm,czyks,
                        patientInfodetail.getAge(),yyghrq,ywckbm,detailBean.getDeptID(),detailBean.getDoctID());
            }
            else {
                ghxh=ifmlessone(tempyyghid,request.getTypeID(),ghfsbm,fbbm,request.getPatientID(),czybm,czyks,patientInfodetail.getAge(),yyghrq,ywckbm,tempghxh,detailBean.getDeptID(),detailBean.getDoctID());
            }
            if(list!=null){
                for (int p=0;p<list.size();p++){
                    mapper.savemzbbrfy(fbbm,ywckbm,list.get(p).getXlbm(),list.get(p).getMxfyxmbm(),czybm,list.get(p).getDlbm(),yyghrq,patientInfodetail.getPatientID(),ghxh,patientInfodetail.getName(),"1",
                            list.get(p).getFydj(),list.get(p).getFydj(),detailBean.getDeptID(),detailBean.getDoctID(),qshnew,jsjlid,"0","1");
                    System.out.print("这是费用单价"+list.get(p).getFydj());
                    fyhj=fyhj+Float.valueOf(list.get(p).getFydj());
                }}
            String hj=String.valueOf(fyhj);
            mapper.updatemzdqqj(qshnew,mzdqpjBean.getQsh(),mzdqpjBean.getJsh(),mzdqpjBean.getFpjlid(),czybm);
            Jsjl_YwxhBean jsjl_ywxhBean=mapper.getJsjlywxh();
            String jsxh=jsjl_ywxhBean.getXh();
            int i=DateUtils.daysBetween(jsjl_ywxhBean.getSsrq());
            if(i>=1){
                jsjlid=ifithanone(tempyyghid,ghxh,czybm,ywckbm,patientInfodetail.getPatientID(),czyks,patientInfodetail.getCardNo(),hj);
            }
            else {
                jsjlid=ifilessone(tempyyghid,ghxh,czybm,ywckbm,patientInfodetail.getPatientID(),czyks,patientInfodetail.getCardNo(),jsxh,hj);
            }
            mapper.updatebrfy(jsjlid,ghxh);
            PayDetailBean p=setPayBean(patientInfodetail,jsjlid,request,czybm,czyxm);
            mapper.saverePaybean(p);
            String autonetid=mapper.GetMaxAutoId();
            AutoOrderBean a=setAutoBean(detailBean,yyghrq,ghxh,yyghid,request,ispay,czybm,czyxm);
            mapper.saveyyjl(a);
            String AutoOrderId=mapper.GetMaxAutoOrderListId();
            mapper.upghbOrderId(AutoOrderId,ghxh);
            //String autonetid=kmapper.GetAutonetId(patientInfodetail.getPatientID());

            kmapper.UpAutonetId(autonetid,ghxh,
                    patientInfodetail.getPatientID(),
                    jsjlid);
            mapper.updateyyclbz(yyghid);
            ExecRegistResponse registResponse=new ExecRegistResponse();
            registResponse=setResponse(detailBean,yyghid,yydjrq,ghxh);
            logger.error("挂号和预约挂号的出参:"+ JSON.toJSONString(registResponse));
            return registResponse;
        }
        return  null;
    }

    /**
     * 当预约挂号ID大于1时m
     */private  String  iftthanone( String yyghid,Long tempyyghid,String czybm,String yyghrq, String ywckbm ,
                                    String brxb,String brnl,String yyys,String yyks, String czyks,String yydjrq,String yyyxrq, int yyzfbz,
                                    PatientInfodetail info,String DAY){
        mapper.updateyyghxh("000001",DateUtils.Getdnowdatexx());
        yyghid=String.valueOf(tempyyghid+1);
        mapper.saveyyghb(yyghid,ywckbm,czybm,info.getPatientID(),yyghrq,info.getName(),brxb,info.getBirthday(),
                info.getAge(),"1",info.getIDCardNo(),info.getAddress(),info.getMobile(),yyys,yyks,yydjrq,yyyxrq,czyks,info.getCardNo(),yyzfbz);
        mapper.updateyzhb(1,0,DAY,yyys);
        return yyghid;
    }
    /**当预约挂号业务序号为当天时**/
    private String  iftlessone( String yyghid,Long tempyyghid,String czybm,String yyghrq, String ywckbm ,
                                String brxb,String brnl,String yyys,String yyks, String czyks,String yydjrq,String yyyxrq, int yyzfbz,
                                PatientInfodetail info,String DAY,String xh){
        int xh1 = Integer.parseInt(xh.trim()) + 1;
        String xh2=mapper.selectywxhbyid(xh1).getXh();
        mapper.updateyyghxh(xh2,DateUtils.Getdnowdatexx());
        yyghid=String.valueOf(tempyyghid+xh1);
        mapper.saveyyghb(yyghid,ywckbm,czybm,info.getPatientID(),yyghrq,info.getName(),brxb,info.getBirthday(),
                info.getAge(),"1",info.getIDCardNo(),info.getAddress(),info.getMobile(),yyys,yyks,yydjrq,yyyxrq,czyks,info.getCardNo(),yyzfbz);;
        mapper.updateyzhb(1,0,DAY,yyys);
        return  yyghid;
    }


    private ExecRegistResponse setResponse(DocDetailBean detailBean,String id,String yyghrq,String mzh){
        ExecRegistResponse response=new ExecRegistResponse();
        response.setResultCode("0");
        response.setResultMsg("挂号成功!");
        response.setDeptName(detailBean.getDepName());
        response.setDoctName(detailBean.getDoctName());
        response.setRankName(detailBean.getRankName());
        response.setSpecialty(detailBean.getSpecialty());
        response.setTreatLocation(detailBean.getTreatLocation());
        response.setWaitNum(detailBean.getWaitNum());
        response.setInvoiceNo(id);
        response.setOpDateTime(yyghrq);
        response.setTimeRegion(detailBean.getTimeRegion());
        response.setTypeName(detailBean.getTypeName());
        response.setHosTranNo(id);
        response.setMzh(mzh);
        return  response;
    }

    private ExecRegistResponse setResponse1(DocDetailBean detailBean,String id,String yyghrq,String mzh,String msg){
        ExecRegistResponse response=new ExecRegistResponse();
        response.setResultCode("0");
        response.setResultMsg(msg);
        response.setDeptName(detailBean.getDepName());
        response.setDoctName(detailBean.getDoctName());
        response.setRankName(detailBean.getRankName());
        response.setSpecialty(detailBean.getSpecialty());
        response.setTreatLocation(detailBean.getTreatLocation());
        response.setWaitNum(detailBean.getWaitNum());
        response.setInvoiceNo(id);
        response.setOpDateTime(yyghrq);
        response.setTimeRegion(detailBean.getTimeRegion());
        response.setTypeName(detailBean.getTypeName());
        response.setHosTranNo(id);
        response.setMzh(mzh);
        return  response;
    }
    /**
     * 当挂号业务序号表大于1
     * @param tempghxh
     * @param ghzlbm
     * @param ghfsbm
     * @param fbbm
     * @param brid
     * @param czybm
     * @param czyks
     * @param brnl
     * @param zcrq
     * @param ywckbm
     */
    private  String ifmthanone(Long tempghxh,String ghzlbm,String ghfsbm,String fbbm,String brid,
                               String czybm,String czyks,String brnl,String zcrq,String ywckbm,String ghks,String jzys){
        mapper.updateghxhywxh("000001",DateUtils.Getdnowdatexx());
        String  ghxh=String.valueOf(tempghxh+1);
        mapper.saveghb(ghxh,ghzlbm,ghfsbm,fbbm,brid,czybm,czyks,
                ghks,brnl,zcrq,zcrq,ywckbm,jzys);
        mapper.updatesfysghf(ghxh);
        return  ghxh;
    }
    /**
     * 当挂号时间等于当天时间
     * @param tempghxh
     * @param ghzlbm
     * @param ghfsbm
     * @param fbbm
     * @param brid
     * @param czybm
     * @param czyks
     * @param brnl
     * @param zcrq
     * @param ywckbm
     * @param xh
     * @return
     */
    private  String ifmlessone(Long tempghxh,String ghzlbm,String ghfsbm,String fbbm,String brid,
                               String czybm,String czyks,String brnl,String zcrq,String ywckbm,String xh,String ghks,String jzys){
        int xh1 = Integer.parseInt(xh.trim()) + 1;
        String xh2=mapper.selectywxhbyid(xh1).getXh();
        mapper.updateghxhywxh(xh2,DateUtils.Getdnowdatexx());
        String  ghxh=String.valueOf(tempghxh+xh1);
        mapper.saveghb(ghxh,ghzlbm,ghfsbm,fbbm,brid,czybm,czyks,
                ghks,brnl,zcrq,zcrq,ywckbm,jzys);
        mapper.updatesfysghf(ghxh);
        return  ghxh;
    }
    /**
     * 当结算记录业务序号时间大于1时执行
     * @param tempjsjlid
     * @param ghxh
     * @param czybm
     * @param ywckbm
     * @param brid
     * @param czyks
     * @param ylkh
     * @return
     */
    private String  ifithanone(Long tempjsjlid,String ghxh,String czybm,String ywckbm,String brid,String czyks,String ylkh,String fyhj){
        mapper.updejsjlywxh("000001",DateUtils.Getdnowdatexx());
        String jsjlid=String.valueOf(tempjsjlid+1);
        JsjlBean jsjlBean=new JsjlBean(jsjlid,ghxh,"1",czybm,ywckbm,brid,fyhj,"0",
                fyhj,"0","0","0" ,"0","0",DateUtils.Getdnowdatexx(),czyks,
                "挂号结算","","0","0","0",ylkh,"0",
                "0","0","0");
        mapper.saveghjsb(jsjlBean);
        return  jsjlid;
    }

    private String  ifilessone(Long tempjsjlid,String ghxh,String czybm,String ywckbm,String brid,String czyks,String ylkh,String xh,String fyhj){
        int xh1 = Integer.parseInt(xh.trim()) + 1;
        String xh2=mapper.selectywxhbyid(xh1).getXh();
        mapper.updejsjlywxh(xh2,DateUtils.Getdnowdatexx());
        String jsjlid=String.valueOf(tempjsjlid+xh1);
        JsjlBean jsjlBean=new JsjlBean(jsjlid,ghxh,"1",czybm,ywckbm,brid,fyhj,"0",
                fyhj,"0","0","0" ,"0","0",DateUtils.Getdnowdatexx(),czyks,
                "挂号结算","","0","0","0",ylkh,"0",
                "0","0","0");
        mapper.saveghjsb(jsjlBean);
        return  jsjlid;
    }
    /**填充支付记录数据**/
    private  PayDetailBean setPayBean(PatientInfodetail pa,String jsxh,ExecRegistRequest r,String czybm,String czyxm){
        PayDetailBean pay=new PayDetailBean();
        if(r.getReqtype().trim().equals("0")){
            pay.setBzms("自助机结算");
        }
        if(r.getReqtype().trim().equals("1")){
            pay.setBzms("微信结算");
        }
        pay.setPayTag(r.getPayTag());
        pay.setCodeTermidNo(r.getCodeTermidNo());
        pay.setPayTranDate(r.getPayTranDate());
        pay.setAddress(pa.getAddress());
        pay.setAutoTranNo(r.getAutoTranNo());
        pay.setBankCardNo(r.getBankCardNo());
        pay.setBankPNo(r.getBankPNo());
        pay.setBankReferNo(r.getBankReferNo());
        pay.setBankTermid(r.getBankTermid());
        pay.setBirthday(pa.getBirthday());
        pay.setCardType(r.getCardType());
        pay.setCodeBuyerAccount(r.getCodeBuyerAccount());
        pay.setBankTranNo(r.getBankTranNo());
        pay.setJsxh(jsxh);
        pay.setCodeTradeOrderNo(r.getCodeTradeOrderNo());
        pay.setMobile(pa.getMobile());
        pay.setName(pa.getName());
        pay.setPayAmt(r.getPayAmt());
        pay.setIDCardNo(pa.getIDCardNo());
        pay.setSex(pa.getSex());
        pay.setUserId(r.getUserID());
        pay.setPayTranTime(r.getPayTranTime());
        pay.setCardNo(r.getCardNo());
        pay.setPatientID(pa.getPatientID());
        pay.setReqtype(r.getReqtype());
        pay.setCzybm(czybm);
        pay.setCzyxm(czyxm);
        return  pay;
    }

    /**填充支付记录数据当预约挂号时候**/
    private  PayDetailBean setPayBean(PatientInfodetail pa,String jsxh,ExecRegistRequest r,String czybm,String czyxm,String AutoOderId){
        PayDetailBean pay=new PayDetailBean();
        if(r.getReqtype().trim().equals("0")){
            pay.setBzms("自助机结算");
        }
        if(r.getReqtype().trim().equals("1")){
            pay.setBzms("微信结算");
        }
        pay.setPayTag(r.getPayTag());
        pay.setCodeTermidNo(r.getCodeTermidNo());
        pay.setPayTranDate(r.getPayTranDate());
        pay.setAddress(pa.getAddress());
        pay.setAutoTranNo(r.getAutoTranNo());
        pay.setBankCardNo(r.getBankCardNo());
        pay.setBankPNo(r.getBankPNo());
        pay.setBankReferNo(r.getBankReferNo());
        pay.setBankTermid(r.getBankTermid());
        pay.setBirthday(pa.getBirthday());
        pay.setCardType(r.getCardType());
        pay.setCodeBuyerAccount(r.getCodeBuyerAccount());
        pay.setBankTranNo(r.getBankTranNo());
        pay.setJsxh(jsxh);
        pay.setCodeTradeOrderNo(r.getCodeTradeOrderNo());
        pay.setMobile(pa.getMobile());
        pay.setName(pa.getName());
        pay.setPayAmt(r.getPayAmt());
        pay.setIDCardNo(pa.getIDCardNo());
        pay.setSex(pa.getSex());
        pay.setUserId(r.getUserID());
        pay.setPayTranTime(r.getPayTranTime());
        pay.setCardNo(r.getCardNo());
        pay.setPatientID(pa.getPatientID());
        pay.setReqtype(r.getReqtype());
        pay.setCzybm(czybm);
        pay.setCzyxm(czyxm);
        if(AutoOderId!=null&&!AutoOderId.isEmpty()){
            pay.setAutoOrderId(AutoOderId);}
        return  pay;
    }
    private AutoOrderBean setAutoBean(DocDetailBean d,String yyghrq,String ghxh,String yyghid,ExecRegistRequest r,String ispay,String czybm,String czyxm){
        String regWay="";
        if(r.getReqtype().trim().equals("0")){
            regWay="自助机挂号";
        }
        if(r.getReqtype().trim().equals("1")){
            regWay="微信挂号";
        }
        AutoOrderBean a=new AutoOrderBean(yyghrq,r.getTypeID(),d.getTypeName(),d.getDepName(),d.getDeptID(),d.getDoctID(),
                d.getDoctName(),d.getRankName(),yyghid,"0",r.getPayAmt(),"0","0",d.getTimeRegion(),
                d.getSpecialty(),"0",regWay,ispay,r.getPatientID(),r.getCardNo(),yyghid,ghxh,czybm,czyxm,d.getBcfabm());
        return a;
    }

    /**获取挂号总费用键值对**/
    public Map<String,String> GetghzfyMap(){
        List<GhzlBean> list=new ArrayList<>();
        list=mapper.Getghzfy();
        Map<String,String>map=new HashMap<>();
        for(int i=0;i<list.size();i++){
            map.put(list.get(i).getGhzlbm(),list.get(i).getGhzf());
        }
        return  map;
    }




}

